
<template>
    <h1>TODO List</h1>
    <div>
        <input type="text" v-model="title" @keydown.enter="addTodo" />
        <ul v-if="todos.length">
            <li v-for="todo in todos">
                <input type="checkbox" v-model="todo.done" />
                <span :class="{ done: todo.done }">{{ todo.title }}</span>
            </li>
        </ul>
        <div v-else>输入待办事项后按 enter 以添加。</div>
        <div>
            <p>{{ active }} / {{ all }}</p>
            <p>
                全部完成
                <input type="checkbox" v-model="allDone" />
            </p>
            <button v-if="active < all" @click="clear">清除完成项</button>
        </div>
    </div>


</template>

<script setup>

import { ref, computed, watchEffect } from "vue";

// todo部分\
let title = ref("")
// let todos = ref([])

// // method 1  storage
// let todos = ref(JSON.parse(localStorage.getItem('todos')||'[]'));
// watchEffect(()=>{
//     localStorage.setItem('todos',JSON.stringify(todos.value))
// });

// method 2
import {useStorage} from "../utils/storage"
let todos = useStorage('todos', [])


function addTodo() {
    todos.value.push(
        { title: title.value, done: false }
    )
    title.value = "";
}
function clear() {
    todos.value = todos.value.filter((v) => !v.done)

}
let active = computed(() => {
    return todos.value.filter((v) => !v.done).length; 
});
let all = computed(() => todos.value.length);
let allDone = computed({
    get: function() {
        return active.value === 0;
    },
    set: function(value) {
        todos.value.forEach((todo) => {
            todo.done = value
        });
    }
});



</script>

<style>
h1 {
    color: red;
}
</style>